package org.jw.wishlist.resolver;

import static com.google.common.base.Preconditions.checkState;
import static org.apache.commons.lang3.ObjectUtils.isNotEmpty;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jw.wishlist.entity.source.ItemSource;
import org.jw.wishlist.resolver.WangYiItemSourceResolver.Response.Item;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @author Jiawei Zhao
 */
@Slf4j
public class WangYiItemSourceResolver extends ItemSourceSupports implements ItemSourceResolver {

  public static final String SOURCE_KEY = "wangyiyanxuan";

  private final ObjectMapper objectMapper;

  public WangYiItemSourceResolver(RestTemplate restTemplate) {
    super(restTemplate);
    this.objectMapper = buildObjectMapper();
  }

  private static ObjectMapper buildObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    return mapper;
  }

  @Override
  public ItemSource resolve(String linkCode) {

    String url = extractUrl(linkCode);
    Response response = deserialize(doRequest(url));
    Item item = response.getItem();

    log.debug("返回值: {}", response);

    return new ProductItemSourceBuilder()
        .itemId(item.getId())
        .key(SOURCE_KEY)
        .linkCode(linkCode)
        .name(item.getName())
        .originUrl(url)
        .pictureUrl(item.getPic())
        .price(item.getPrice())
        .build();
  }

  private String doRequest(String url) {
    ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
    if (response.getStatusCode().is3xxRedirection()) {
      String location = response.getHeaders().getFirst(HttpHeaders.LOCATION);
      if (isNotEmpty(location)) {
        return doRequest(location);
      }
    }

    String str = response.getBody();
    checkState(isNotEmpty(str), "解析失败");
    return str;
  }

  private Response deserialize(String content) {
    try {
      return objectMapper.readValue(content, Response.class);
    } catch (JsonProcessingException e) {
      throw new IllegalStateException("解析失败", e);
    }
  }

  @Data
  static class Response {

    private Item item;

    @Data
    static class Item {

      private String id;

      private String name;

      @JsonProperty("primaryPicUrl")
      private String pic;

      @JsonProperty("retailPrice")
      private String price;


    }

  }
}
